<template>
	<view>
		<button @click="goMain">返回首页</button>
		<!-- 点击按钮触发微信登录授权 -->
		<button @click="getUserProfile">微信授权</button>
		<view class="userinfo-box" v-if="isAutorized">
			<text class="text-name">{{ userinfo.nickName }}</text>
			<image class="img-avar" :src="userinfo.avatarUrl"></image>
		</view>
	</view>
</template>

<script>
	
	
	export default {
			data() {
				return {
					isAutorized: false,
					userinfo: {
						avatarUrl: '',
						nickName: '',
						openid: ''
					},
					weixin: {
						jscode2sessionUrl: 'jscode2session',
						appid: 'wx2ccba4b8e7d71d72',
						secret: '16ae5e2804234db4d3dfd9653159493d'
					}
				}
			},
			methods: {
				getUserProfile() {
					const that = this;
					uni.showLoading({
						title: '授权进行中...'
					})
					uni.getUserProfile({
						lang: 'zh_CN',
						desc: '授权获得更多服务',
						success(result) {
							const {
								avatarUrl,
								nickName
							} = result.userInfo;
							uni.login({
								provider: 'weixin',
								success(res) {
									//显示code
									console.log(res);
									let url =
										`https://api.weixin.qq.com/sns/${that.weixin.jscode2sessionUrl}?appid=${that.weixin.appid}&secret=${that.weixin.secret}&js_code=${res.code}&grant_type=authorization_code `;
									uni.request({
										url: url,
										success(res2) {
											that.userinfo.avatarUrl = avatarUrl;
											that.userinfo.nickName = nickName;
											that.userinfo.openid = res2.data.openid;
											//保存授权状态
											// that.userStore.saveWxUserinfo(that.userinfo);
											that.isAutorized = true
											console.log(that.userinfo);
											//将头像和openid保存到localstorage
											uni.setStorageSync('nickName', nickName);
											uni.setStorageSync('avatarUrl', avatarUrl);
											uni.setStorageSync('openid', res2.data.openid);
										}
									})
	
								}
							})
						},
						fail() {
							title: '授权失败'
						},
						complete() {
							uni.hideLoading();
						},
	
					})
	
				},
				goMain(){
					uni.switchTab({
						url:"/pages/index/index"
					})
				}
			}
		}

</script>

